# 沪市指数可视化
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.arima_model import ARIMA
import statsmodels.api as sm
from itertools import product
from datetime import datetime, timedelta
import calendar
import warnings

warnings.filterwarnings('ignore')
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签

# 数据加载
df = pd.read_csv(r'E:\课程作业\深度学习\课程设计\sh_index.csv', encoding='gb2312')
df

# 选择我们要分析的列
df = df[['date', 'close']]
df['date'] = pd.to_datetime(df['date'], format='%Y%m%d')
df
# 对列名进行修改
df.columns = ['Timestamp', 'Price']
df

# 将时间作为df的索引
df = df.sort_values('Timestamp', ascending=True)
df.Timestamp = pd.to_datetime(df.Timestamp)
df.index = df.Timestamp
# 数据探索
df.head()

# 返回三个部分 trend（趋势），seasonal（季节性）和residual (残留)
# price = trend + seasonal + resid, 设置period = 1年内的有效数据个数
result = sm.tsa.seasonal_decompose(df.Price, period=250)
result.plot()
plt.show()

# 按照月，季度，年来统计
df_month = df.resample('M').mean()
df_Q = df.resample('Q-DEC').mean()
df_year = df.resample('A-DEC').mean()

# 按照天，月，季度，年来显示沪市指数的走势
fig = plt.figure(figsize=[15, 7])
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.suptitle('沪市指数', fontsize=20)
plt.subplot(221)
plt.plot(df.Price, '-', label='按天')
plt.legend()
plt.subplot(222)
plt.plot(df_month.Price, '-', label='按月')
plt.legend()
plt.subplot(223)
plt.plot(df_Q.Price, '-', label='按季度')
plt.legend()
plt.subplot(224)
plt.plot(df_year.Price, '-', label='按年')
plt.legend()
plt.show()